'use strict';

const Service = require('egg').Service;

class PatientService extends Service {

  async getPatientDetail({ patientId }) {
    const query = { _id: patientId };

    const patient = await this.ctx.model.Patient.findOne(query).lean();

    if (!patient) {
      return [];
    }

    return [ patient ];
  }

  async getPatientList(query, option) {

    const totalCount = await this.ctx.model.Patient.count(query);
    const patientList = await this.ctx.model.Patient.find(query, {}, option).exec();

    if (patientList.length === 0) {
      return [ [], 0 ];
    }

    return [ patientList, totalCount ];
  }

  async removePatient({userId, patientId}) {
    await this.ctx.model.Patient.remove({
      user_id: userId,
      patient_id: patientId,
    });
    return [ patientId ];
  }

  async newPatient({
    userId,
    image,
    name,
    idCardType,
    idCardNum,
    sex,
    birthday,
    address,
    addressHold,
  }) {
    const p = new this.ctx.model.Patient();
    p.user_id = userId;
    p.image = image;
    p.name = name;
    p.id_card_type = idCardType;
    p.id_card_num = idCardNum;
    p.sex = sex;
    p.birthday = birthday;
    p.address = address;
    p.address_hold = addressHold;
    p.state = 'A';
    await p.save();

    return [ p._id ];
  }
}

module.exports = PatientService;
